package com.nancy.springioc.bean.factory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 封装PropertyValue的迭代器
 */
public class MutablePropertyValue implements Iterable<PropertyValue> {
    // 属性值列表
    private final List<PropertyValue> propertyValueList;

    // 无参构造函数
    public MutablePropertyValue() {
        this.propertyValueList = new ArrayList<PropertyValue>();
    }

    // 构造函数
    public MutablePropertyValue(List<PropertyValue> propertyValueList) {
        if (propertyValueList == null) {
            this.propertyValueList = new ArrayList<PropertyValue>();
        } else {
            this.propertyValueList = propertyValueList;
        }
    }

    // 根据proprietyname获取属性值
    public PropertyValue getPropertyValue(String propertyName) {
        for (PropertyValue pv : this.propertyValueList) {
            if (propertyName.equals(pv.getName())) {
                return pv;
            }
        }
        return null;
    }

    // 判断集合是否为空
    public boolean isEmpty() {
        return this.propertyValueList.isEmpty();
    }


    // 添加属性值
    public MutablePropertyValue addPropertyValue(PropertyValue propertyValue) {
        //判断是否重复添加
        for (int i = 0; i < propertyValueList.size(); i++) {
            PropertyValue pv = propertyValueList.get(i);
            if (propertyValue.getName().equals(pv.getName())) {
                propertyValueList.set(i, propertyValue);
                return this;//目的是链式编程 返回this
            }
        }
        this.propertyValueList.add(propertyValue);
        return this;
    }

    //判断是否有指定属性值的存在
    public boolean containsPropertyValue(String propertyName) {
        return getPropertyValue(propertyName) != null;
    }


    // 返回迭代器
    @Override
    public Iterator<PropertyValue> iterator() {
        return propertyValueList.iterator();
    }
}
